package com.example.noteapp;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements NoteAdapter.OnNoteClickListener {
    private RecyclerView notesRecyclerView;
    private NoteAdapter noteAdapter;
    private TextView emptyNotesText;
    private FloatingActionButton addNoteFab;
    private List<Note> noteList = new ArrayList<>();
    private static final int EDIT_NOTE_REQUEST = 1;

    private static final String NOTES_FILE = "notes.dat";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化UI组件
        notesRecyclerView = findViewById(R.id.notes_recycler_view);
        emptyNotesText = findViewById(R.id.empty_notes_text);
        addNoteFab = findViewById(R.id.add_note_fab);

        // 设置RecyclerView
        notesRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        noteAdapter = new NoteAdapter(this);
        noteAdapter.setOnNoteClickListener(this);
        notesRecyclerView.setAdapter(noteAdapter);

        // 加载已保存的笔记，如果没有则添加示例笔记
        if (!loadNotes()) {
            addSampleNotes();
        }

        // 设置添加笔记按钮点击事件
        addNoteFab.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, EditNoteActivity.class);
            startActivityForResult(intent, EDIT_NOTE_REQUEST);
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 应用暂停时保存笔记数据
        saveNotes();
    }

    // 添加一些示例笔记用于演示
    private void addSampleNotes() {
        Note note1 = new Note("第一条笔记", "这是一个示例笔记内容，您可以编辑或删除它。");
        note1.setId(1);
        noteList.add(note1);

        Note note2 = new Note("第二条笔记", "这是另一个示例笔记，展示了笔记应用的基本功能。");
        note2.setId(2);
        noteList.add(note2);

        updateNotesList();
    }

    // 保存笔记数据到文件
    private void saveNotes() {
        try {
            FileOutputStream fileOut = openFileOutput(NOTES_FILE, MODE_PRIVATE);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(noteList);
            out.close();
            fileOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件加载笔记数据
    @SuppressWarnings("unchecked")
    private boolean loadNotes() {
        try {
            FileInputStream fileIn = openFileInput(NOTES_FILE);
            ObjectInputStream in = new ObjectInputStream(fileIn);
            noteList = (List<Note>) in.readObject();
            in.close();
            fileIn.close();
            updateNotesList();
            return true;
        } catch (IOException | ClassNotFoundException e) {
            // 如果文件不存在或读取失败，则返回false
            return false;
        }
    }

    private void updateNotesList() {
        noteAdapter.setNoteList(noteList);
        // 根据笔记列表是否为空显示或隐藏空状态文本
        if (noteList.isEmpty()) {
            emptyNotesText.setVisibility(View.VISIBLE);
            notesRecyclerView.setVisibility(View.GONE);
        } else {
            emptyNotesText.setVisibility(View.GONE);
            notesRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK && data != null) {
            Note updatedNote = (Note) data.getSerializableExtra("note");
            boolean isNewNote = data.getBooleanExtra("is_new", false);

            if (isNewNote) {
                // 新增笔记
                updatedNote.setId(System.currentTimeMillis());
                noteList.add(0, updatedNote); // 添加到列表顶部
            } else {
                // 更新已有笔记
                for (int i = 0; i < noteList.size(); i++) {
                    if (noteList.get(i).getId() == updatedNote.getId()) {
                        noteList.set(i, updatedNote);
                        break;
                    }
                }
            }

            updateNotesList();
        }
    }

    @Override
    public void onNoteClick(Note note) {
        // 点击笔记进入编辑界面
        Intent intent = new Intent(MainActivity.this, EditNoteActivity.class);
        intent.putExtra("note", note);
        startActivityForResult(intent, EDIT_NOTE_REQUEST);
    }

    @Override
    public void onNoteLongClick(Note note) {
        // 长按笔记显示删除对话框
        new AlertDialog.Builder(this)
                .setTitle(R.string.delete_dialog_title)
                .setMessage(R.string.delete_dialog_message)
                .setPositiveButton(R.string.delete_dialog_confirm, (dialog, which) -> {
                    noteList.remove(note);
                    updateNotesList();
                    Toast.makeText(MainActivity.this, R.string.delete_note, Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton(R.string.delete_dialog_cancel, null)
                .show();
    }
}